This repository has no description
1import { createHmac } from "node:crypto";
2import { error } from "@sveltejs/kit";
3import { getConfig } from "$lib/server/config";
4import type { RequestHandler } from "./$types";
5
6// half a day, the same as what the service puts on the image
7const MAX_AGE = 43200;
8
9const DID = /^did:[a-z]+:[a-zA-Z0-9._:%-]{1,256}$/;
10
11// the service ignores anything else, so there is no point passing it on
12const PASSED_THROUGH = ["size", "format"];
13
14export const GET: RequestHandler = ({ params, url }) => {
15 const did = params.did;
16 if (!DID.test(did)) error(400, "Not a did");
17
18 const { avatarUrl, avatarSecret } = getConfig();
19 if (!avatarSecret) error(404, "Avatars are not configured");
20
21 const query = new URLSearchParams();
22 for (const key of PASSED_THROUGH) {
23 const value = url.searchParams.get(key);
24 if (value) query.set(key, value);
25 }
26
27 const signature = createHmac("sha256", avatarSecret).update(did).digest("hex");
28 const target = `${avatarUrl}/${signature}/${did}${query.size ? `?${query}` : ""}`;
29 return new Response(null, {
30 status: 302,
31 headers: { location: target, "cache-control": `public, max-age=${MAX_AGE}` }
32 });
33};